package com.example.filefusion.service;

import io.minio.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
public class FileStorageService {

    private static final Logger logger = LoggerFactory.getLogger(FileStorageService.class);

    @Autowired
    private MinioClient minioClient;

    @Value("${minio.bucket-name}")
    private String bucketName;

    public String uploadFile(MultipartFile file) throws Exception {
        logger.info("开始上传文件: originalFilename={}, size={}", file.getOriginalFilename(), file.getSize());
        
        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String fileExtension = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        String fileName = UUID.randomUUID().toString() + fileExtension;
        logger.info("生成唯一文件名: originalFilename={}, storedFileName={}", originalFilename, fileName);

        // 检查存储桶是否存在，不存在则创建
        logger.info("检查存储桶是否存在: bucketName={}", bucketName);
        boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        if (!exists) {
            logger.info("存储桶不存在，正在创建: bucketName={}", bucketName);
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            logger.info("存储桶创建成功: bucketName={}", bucketName);
        } else {
            logger.info("存储桶已存在: bucketName={}", bucketName);
        }

        // 上传文件
        logger.info("开始上传文件到 MinIO: bucketName={}, storedFileName={}", bucketName, fileName);
        minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(bucketName)
                        .object(fileName)
                        .stream(file.getInputStream(), file.getSize(), -1)
                        .contentType(file.getContentType())
                        .build()
        );
        logger.info("文件上传成功: storedFileName={}", fileName);

        return fileName;
    }

    public InputStream downloadFile(String filename) throws Exception {
        logger.info("开始下载文件: filename={}", filename);
        InputStream inputStream = minioClient.getObject(
                GetObjectArgs.builder()
                        .bucket(bucketName)
                        .object(filename)
                        .build()
        );
        logger.info("文件下载准备完成: filename={}", filename);
        return inputStream;
    }
}